
const { Wallet, Contract, ContractFactory, getDefaultProvider } = require('ethers');
const logger = require("../../utils/logger");

const getWallet = async () => {
    const privateKey = process.env["ETH_PRIVATE_KEY"];
    if (privateKey) {
        logger.debug("provider default: " + process.env["NET"]);
        let provider = getDefaultProvider(process.env["NET"]); // chain env
        const hexlifiedPrivateKey = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
        return new Wallet(hexlifiedPrivateKey, provider);
    }
    throw new Error("No private key found in ETH_PRIVATE_KEY");
};

const deploy = async (parameters,abi,bin) => {
    let wallet = await getWallet();
    let factory = new ContractFactory(abi,bin,wallet)
    let contract = await factory.deploy(...parameters)
    logger.debug(`Document Store contract address is ${contract.address}`);
    logger.debug(`Document Store contract deployTransaction is ${contract.deployTransaction.hash}`);
    await contract.deployed()
    return contract
};

const send = async (abi, parameters,ContractAddress,ContractAbi, readOnly = false) => {
    logger.debug("DocumentStoreService send: ", abi, parameters);
    let wallet = await getWallet();
    const gasPrice = await wallet.provider.getGasPrice(); 
    let contract = new Contract(ContractAddress, ContractAbi, wallet);
    const transaction = await contract[abi](...parameters, { gasPrice: gasPrice.mul(1) });
    let receipt;
    if (readOnly) {
        receipt = transaction;
    } else {
        logger.debug(`Waiting for transaction ${transaction.hash} to be mined`);
        receipt = transaction.wait();
    }
    return receipt;
}

module.exports = {
    deploy,
    send
}
